from qcloudsms_py import SmsSingleSender
from . import settings
from taotao.utils.logger import log
from qcloudsms_py.httpclient import HTTPError
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

#生成一个四位随机验证码
def get_code():
    import random
    s_code = ''
    for i in range(4):
        s_code += str(random.randint(0,9))
    return s_code

def send_message(phone,code):
    ssender = SmsSingleSender(settings.appid, settings.appkey)
    params = [code, '3']  # 当模板没有参数时，`params = []` #随机验证码 #这里的3是3分钟
    try:
        result = ssender.send_with_param(86, phone, settings.template_id, params, sign=settings.sms_sign, extend="", ext="")
        print(result)  #{'result': 0, 'errmsg': 'OK', 'ext': '', 'sid': '2019:8911867479998208871', 'fee': 1, 'isocode': 'CN'}
        if result.get('result') == 0: #表示发送成功
            return True
        else:
            log.error('手机号：%s,短信发送失败， 错误为：%s'%(phone, result.get('errmsg')))
            return False
    except Exception as e:
        #当有错误，调用log对象来记录错误
        log.error('手机号：%s,短信发送失败， 错误为：%s'%(phone, str(e)))

